package uw10.app.display;

import uw10.app.data.GraphBounds;
import uw10.app.data.GraphData;
import uw10.app.data.GraphIndicator;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.Paint.Style;
import android.graphics.Rect;
import android.graphics.Typeface;

public class GraphRenderer
{
	public static final int LABEL_TITLE = 1;
	
	private Canvas c;
	
	public GraphRenderer()
	{
		c = new Canvas();
	}
	
	public void render(Bitmap bmp, String label, int type, int color, int size)
	{
		c.setBitmap(bmp);
		
		if (type == LABEL_TITLE)
		{
			Paint p = new Paint();
			p.setColor(color);
			p.setTextAlign(Align.CENTER);
			p.setTextSize(size);
			p.setTypeface(Typeface.SANS_SERIF);
			p.setAntiAlias(true);
			
			Rect r = new Rect();
			p.getTextBounds(label, 0, label.length(), r);
			
			c.drawText(label, bmp.getWidth() / 2, (int) (r.height() * 1.5), p);
		}
	}
	
	public void render(Bitmap bmp, GraphBounds bounds, GraphData data, int color, int width)
	{
		c.setBitmap(bmp);
		
		Paint p = new Paint();
		p.setColor(color);
		p.setStyle(Style.STROKE);
		p.setStrokeWidth(width);
		p.setAntiAlias(true);
		
		double scaleX = ((double)bmp.getWidth()) / (bounds.tMax - bounds.tMin);
		double scaleY = ((double)bmp.getHeight()) / (bounds.vMax - bounds.vMin);
		
		int x = (int) ((data.time[0] - bounds.tMin) * scaleX);
		int y = (int) ((data.value[0] - bounds.vMin) * scaleY);
		for (int i = 1; i < data.length; i++)
		{
			int nX = (int) ((data.time[i] - bounds.tMin) * scaleX);
			int nY = (int) ((data.value[i] - bounds.vMin) * scaleY);
			
			c.drawLine(x, y, nX, nY, p);
			
			x = nX;
			y = nY;
		}
	}
	
	public void render(Bitmap bmp, GraphBounds bounds, GraphIndicator indi, int color, int width, int arrow)
	{
		c.setBitmap(bmp);
		
		Paint p = new Paint();
		p.setColor(color);
		p.setStyle(Style.STROKE);
		p.setStrokeWidth(width);
		p.setAntiAlias(true);
		
		double scaleX = ((double)bmp.getWidth()) / (bounds.tMax - bounds.tMin);
		double scaleY = ((double)bmp.getHeight()) / (bounds.vMax - bounds.vMin);
		
		int x = (int) ((indi.time - bounds.tMin) * scaleX);
		int y1 = (int) ((indi.value1 - bounds.vMin) * scaleY);
		int y2 = (int) ((indi.value2 - bounds.vMin) * scaleY);
		
		c.drawLine(x, y1, x, y2, p);
		
		if (arrow != 0)
		{
			if (y2 > y1)
			{
				c.drawLine(x - arrow, y2 - arrow, x, y2, p);
				c.drawLine(x + arrow, y2 - arrow, x, y2, p);
			}
			else
			{
				c.drawLine(x - arrow, y2 + arrow, x, y2, p);
				c.drawLine(x + arrow, y2 + arrow, x, y2, p);
			}
		}
	}
}
